package org.tissou.server.Operations;

import org.tissou.client.Services.Compte;
import org.tissou.client.Services.ProprietaireInfos;
import org.tissou.client.Services.CategorieInfos;
import org.tissou.client.Services.MonException;
import org.tissou.server.Utils.InterfaceMySQL;

import java.util.Date;
import java.util.Locale;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.text.*;

/**
 * Created by IntelliJ IDEA.
 * User: Claire
 * Date: 11-Jan-2009
 * Time: 14:30:08
 * To change this template use File | Settings | File Templates.
 */
public class Transaction {

  private static final DateFormat SQL_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");

  private static final DecimalFormatSymbols SYMBOLS = new DecimalFormatSymbols();
  private static final NumberFormat FLOAT_FORMAT;

  static {
    SYMBOLS.setDecimalSeparator('.');
    FLOAT_FORMAT = new DecimalFormat("#0.00", SYMBOLS);
    FLOAT_FORMAT.setGroupingUsed(false);
  }

  Date date;
  Compte compte;
  CategorieInfos categorie;
  String libelle;
  Float somme;
  boolean verifie;
  ProprietaireInfos tiers;

  public Transaction(Date dat, Compte com, CategorieInfos cat, String lib, Float som, boolean ver,
                     ProprietaireInfos tie){
    date = dat;
    compte = com;
    categorie = cat;
    libelle = lib;
    somme = som;
    verifie = ver;
    tiers = tie;
  }

  public void Entrer_Transaction() {

    try {
      InterfaceMySQL.getInstance().EnvoyerQuery(
        String.format("INSERT INTO transactions(Date, NoCompte, Categorie, Libelle, Somme, Verifie, Tiers)" +
              " VALUES('%s', '%d', '%s', '%s', '%s', '%d', %s)",
          SQL_DATE_FORMAT.format(date), compte.getNoCompte(), categorie.getNom(), libelle.replace("'", "\\'"), FLOAT_FORMAT.format(somme), verifie ? 1 : 0,
            tiers == null ? "NULL" : String.format("'%s'", tiers.getNom())));
    } catch (SQLException e) {
      throw new MonException("Je n'ai pas pu rentrer ta transaction", e);
    }
  }
}
